package com.space.school.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class SpaceJDBCUtils {
    // 1.定义成员变量 DataSource
    private static DataSource ds;

    // 2.静态代码块预先加载配置文件 druid.properties中的内容
    static {
        Properties ps = new Properties();
        try {
            // 使用Properties加载druid.properties文件
            ps.load(SpaceJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            // 初始化 DataSource
            ds = DruidDataSourceFactory.createDataSource(ps);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//    DataSource ds数据来源让外部可以取到
     public static DataSource getDs(){
        return ds;
     }
    // 获取连接方法
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    // 关闭流
    public static void close(Statement stmt, Connection conn) {
        close(null, stmt, conn);
    }

    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
